package com.itheima.night;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings(value = "all")
public class Demo04 {
    public static void main(String[] args) throws DocumentException {
        //创建一个解析器对象
        SAXReader saxReader = new SAXReader();
        //利用解析器对象将xml文件加载到内存中，并返回一个文档对象
        Document document = saxReader.read(new File("day18\\XML\\Students02.xml"));
        //根据文档对象获取根标签
        Element rootElement = document.getRootElement();
        //获取根标签下指定的对象元素数组
        List<Element> elements = rootElement.elements("Student");

        //新建一个集合，用来存储Student对象
        ArrayList<Student> studentList = new ArrayList<>();

        //遍历标签数组
        for (Element element : elements) {
            //获取标签属性
            Attribute attribute = element.attribute("id");
            //根据标签的键获取值
            String id = attribute.getValue();

            //获取标签内容
            Element nameElement = element.element("name");
            String name = nameElement.getText();

            Element ageElement = element.element("age");
            int age = Integer.parseInt(ageElement.getText());

            //将Student对象进行封装，并添加到集合
            Student s = new Student(id,name,age);
            studentList.add(s);
        }

        for (Student student : studentList) {
            System.out.println(student);
        }
    }
}
